package com.cxh.controller;

import com.cxh.entity.Item;
import com.cxh.enums.ExceptionInfoEnum;
import com.cxh.exception.SsmException;
import com.cxh.service.ItemService;
import com.cxh.vo.ResultVo;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.beans.factory.annotation.Value;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;


@Controller
@Slf4j
@RequestMapping("/item")
@SessionAttributes
public class ItemController {

    @Value("${pic.maxSize}")
    private Long picMaxSize;

    @Value("${pic.types}")
    private String types;


    @Autowired
    public ItemService itemService;

    //    localhost/item/list
    //展示商品信息页面
    @GetMapping("/list")
    public String showlist(
            String name,
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "5") Integer size,
            Model model) {

        PageInfo<Item> pageInfo = itemService.findProductByNameLimit(name, page, size);

        model.addAttribute("pageInfo", pageInfo);
        model.addAttribute("name", name);
        return "item/item_list";
    }

    //      localhost/item/add-ui
    @GetMapping("/add-ui")
    public String addUI() {
        return "item/item_add";

    }

    //添加商品信息
    @PostMapping("/add")
    @ResponseBody
    public ResultVo add(
            MultipartFile picFile,
            @Valid Item item,
            BindingResult bindingResult,
            HttpServletRequest request
    ) throws IOException {
        if (picFile == null || picFile.getSize() == 0) {
            log.info("【添加商品】 商品图片为必传项,岂能不传!!");
            throw new SsmException(ExceptionInfoEnum.PARAM_ERROR.getCode(), "商品图片为必传项,岂能不传!!");
        }

        if (picFile.getSize() > picMaxSize) {
            log.info("【添加商品】 图片大小过大, size = {}", picFile.getSize());
            throw new SsmException(ExceptionInfoEnum.PIC_GREATER);
        }

        List<String> list = Arrays.asList(types.split(","));
        String fileName = picFile.getOriginalFilename();
        String typeName = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
        if (!list.contains(typeName)) {
            log.info("【添加商品】 图片类型不正确!! typeName = {}", typeName);
            throw new SsmException(ExceptionInfoEnum.PIC_TYPE_ERROR);
        }


        BufferedImage image = ImageIO.read(picFile.getInputStream());
        if (image == null) {
            log.info("【添加商品】 图片已损坏!! picFile = {}", picFile);
            throw new SsmException(ExceptionInfoEnum.PIC_BREAK);
        }
        String newName = UUID.randomUUID().toString() + "." + typeName;
        String path = request.getServletContext().getRealPath("/") + "static/images/" + newName;
        File file = new File(path);
        if (!file.getParentFile().exists()) {
            file.getParentFile().mkdirs();
        }
        //保存到本地
        IOUtils.copy(picFile.getInputStream(), new FileOutputStream(file));
        String pic = request.getContextPath() + "/static/images/" + newName;
        item.setPic(pic);

        if (bindingResult.hasErrors()) {
            String msg = bindingResult.getFieldError().getDefaultMessage();
            log.info("【添加商品】参数不正确 item = {},msg = {}", item, msg);
            throw new SsmException(ExceptionInfoEnum.PARAM_ERROR.getCode(), msg);
        }

        itemService.add(item);

        return new ResultVo(0, "成功", null);
    }

    @DeleteMapping("/del/{id}")
    @ResponseBody
    public ResultVo del(@PathVariable Integer id) {
        itemService.delete(id);

        return new ResultVo(0, "成功", null);
    }

    @GetMapping("/update-ui")
    public String updateUi(Integer id, Model model) {
        Item item = itemService.findEntityById(id);
        model.addAttribute("item", item);

        return "item/item_update";
    }

    @PostMapping("/update")
    @ResponseBody
    public ResultVo update(
            MultipartFile picFile,
            @Valid Item item,
            BindingResult bindingResult,
            HttpServletRequest request
    ) throws IOException {

        if (picFile != null) {
            if (picFile.getSize() > picMaxSize) {
                log.info("【修改商品】 图片大小过大, size = {}", picFile.getSize());
                throw new SsmException(ExceptionInfoEnum.PIC_GREATER);
            }

            List<String> list = Arrays.asList(types.split(","));
            String fileName = picFile.getOriginalFilename();
            String typeName = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
            if (!list.contains(typeName)) {
                log.info("【修改商品】 图片类型不正确!! typeName = {}", typeName);
                throw new SsmException(ExceptionInfoEnum.PIC_TYPE_ERROR);
            }


            BufferedImage image = ImageIO.read(picFile.getInputStream());
            if (image == null) {
                log.info("【修改商品】 图片已损坏!! picFile = {}", picFile);
                throw new SsmException(ExceptionInfoEnum.PIC_BREAK);
            }
            String newName = UUID.randomUUID().toString() + "." + typeName;
            String path = request.getServletContext().getRealPath("/") + "static/images/" + newName;
            File file = new File(path);
            if (!file.getParentFile().exists()) {
                file.getParentFile().mkdirs();
            }
            //保存到本地
            IOUtils.copy(picFile.getInputStream(), new FileOutputStream(file));
            String pic = request.getContextPath() + "/static/images/" + newName;
            item.setPic(pic);

            if (bindingResult.hasErrors()) {
                String msg = bindingResult.getFieldError().getDefaultMessage();
                log.info("【修改商品】参数不正确 item = {},msg = {}", item, msg);
                throw new SsmException(ExceptionInfoEnum.PARAM_ERROR.getCode(), msg);
            }
        } else {

            if (bindingResult.hasErrors()) {
                String msg = bindingResult.getFieldError().getDefaultMessage();
                log.info("【修改商品】参数不正确 item = {},msg = {}", item, msg);
                throw new SsmException(ExceptionInfoEnum.PARAM_ERROR.getCode(), msg);
            }

        }

        itemService.updateEntityById(item);

        return new ResultVo(0, "成功", null);


    }
}
